package com.cjj.navtong;

import java.io.IOException;
import java.io.StringReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.util.ArrayList;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import android.os.Handler;
import android.os.Message;
import android.util.Xml;

import com.cjj.navtong.db.Child;
import com.cjj.navtong.utils.LocalUtils;

public class UDPReceiveStr {
	private byte[] buffer = new byte[1024];
	private DatagramSocket ds = null;
	private DatagramPacket packet = null;
	private InetSocketAddress socketAddress = null;

	private Handler mHandler;
	/**
	 * 构造函数，绑定主机和端口.
	 * 
	 * @param host
	 *            主机
	 * @param port
	 *            端口
	 * @throws Exception
	 */
	public UDPReceiveStr(int port,Handler mHandler) throws Exception {
		socketAddress = new InetSocketAddress(port);   
		ds = new DatagramSocket(socketAddress);
		this.mHandler = mHandler;
//		Message msg = new Message();
//		msg.obj = "可以接收信息";
//		mHandler.sendMessage(msg);
		//System.out.println("可以接收信息");
	}

	/**
	 * 接收数据包，该方法会造成线程阻塞.
	 * @return 返回接收的数据串信息
	 * @throws IOException
	 * @throws XmlPullParserException 
	 */
	public final void receive() throws IOException, XmlPullParserException {
		ArrayList<Child> list = new ArrayList<Child>();
		packet = new DatagramPacket(buffer, buffer.length);
		ds.receive(packet);
		
		
		// Test for local data
//		InputStream is = getClass().getClassLoader().getResourceAsStream("M03104_AMP_130161165407607422.xml");
//		XmlPullParser parser=Xml.newPullParser();
//		parser.setInput(is, "utf-8");
		
		//Test for socket receiver
		String info = new String(packet.getData(), 0, packet.getLength());
		XmlPullParser parser=Xml.newPullParser();
		parser.setInput(new StringReader(info));
		
		int event=parser.getEventType();
		while (event!=XmlPullParser.END_DOCUMENT) {
			switch (event) {
			   case XmlPullParser.START_DOCUMENT:
					break;
			   case XmlPullParser.START_TAG:
					if("DispersingResponsion".equals(parser.getName())){
						int count=parser.getAttributeCount();
						Child child = new Child();
						for(int i=0;i<count;i++){
							String responsion = "";
							String time = "";
							String key=parser.getAttributeName(i);
							if("Responsion".equals(key)){
								responsion=parser.getAttributeValue(i);	
								child.responsion = responsion;
							}else if("Time".equals(key)){
								time=parser.getAttributeValue(i);
								child.time = time;
							}
						}
						list.add(child);
					}
						break;
				case XmlPullParser.END_TAG:
						break;
						
				default:
					break;
				}
				event=parser.next();
			}
				

			Message msg = new Message();
			msg.obj = list;
			mHandler.sendMessage(msg);
			//将文件存储在sd卡中
			LocalUtils.storeFile(info);
//		
//		System.out.println("接收信息：" + info);
//		Message msg = new Message();
//		msg.obj ="接收信息：" + info;
//		mHandler.sendMessage(msg);
		
	}

	/**
	 * 将响应包发送给请求端.
	 * 
	 * @param bytes
	 *            回应报文
	 * @throws IOException
	 */
	public final void response(String info) throws IOException {
		System.out.println("客户端地址 : " + packet.getAddress().getHostAddress() + ",端口：" + packet.getPort());
//		Message msg = new Message();
//		msg.obj ="客户端地址 : " + packet.getAddress().getHostAddress() + ",端口：" + packet.getPort();
//		mHandler.sendMessage(msg);
		DatagramPacket dp = new DatagramPacket(buffer, buffer.length, packet.getAddress(), packet.getPort());
		dp.setData(info.getBytes());
		ds.send(dp);
	}

	/**
	 * 关闭udp监听口.
	 */
	public final void close() {
		try {
			ds.close();
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}
	
}
